if TheNet:IsDedicated() then return end

local MUSIC_VOLUME_OVERRIDES =
{
	["dontstarve/music/music_danger_winter"] = 0.5,
}

AddComponentPostInit("dynamicmusic", function(self, inst)
	local _soundemitter = nil
	local _triggeredevent = nil
	local _triggeredlevel = nil
	
	local OnPlayerActivated = nil
	local StartTriggeredDanger = nil
	
	local function StartTriggeredDangerEX(player, data, ...)
		local name = data ~= nil and data.name or "default"
		local level = data ~= nil and data.level or 1
		if _triggeredevent == name or _triggeredlevel == level or not Waffles.GetUpvalue(StartTriggeredDanger, "_triggeredlevel") then
			_triggeredevent = name
			_triggeredlevel = level
			return StartTriggeredDanger(player, data, ...)
		end
	end
	
	local function _OnPlayerActivated(inst, player)
		inst:RemoveEventCallback("playeractivated", _OnPlayerActivated)	
		
		for i, v in ipairs(inst.event_listening.playeractivated[inst]) do
			local StartPlayerListeners = Waffles.GetUpvalue(v, "StartPlayerListeners")
			if StartPlayerListeners ~= nil then
				StartTriggeredDanger = Waffles.GetUpvalue(StartPlayerListeners, "StartTriggeredDanger")
				if StartTriggeredDanger ~= nil then
					OnPlayerActivated = v
					break
				end
			end
		end
		
		if StartTriggeredDanger ~= nil then
			inst:RemoveEventCallback("triggeredevent", StartTriggeredDanger, player)			
			inst:ListenForEvent("triggeredevent", StartTriggeredDangerEX, player)
			
			Waffles.SetUpvalue(OnPlayerActivated, "StartPlayerListeners", "StartTriggeredDanger", StartTriggeredDangerEX)
			Waffles.SetUpvalue(OnPlayerActivated, "StopPlayerListeners", "StartTriggeredDanger", StartTriggeredDangerEX)
		end
	end
		
	local SoundEmitter = setmetatable(
	{
		PlaySound = function(self, sound, type, volume, ...)
			if MUSIC_VOLUME_OVERRIDES[sound] ~= nil then
				volume = (volume or 1) * MUSIC_VOLUME_OVERRIDES[sound]
			end
			return _soundemitter:PlaySound(sound, type, volume, ...)
		end,
	},
	{
		__index = function(table, key)
			table[key] = function(self, ...)
				return _soundemitter[key](_soundemitter, ...)
			end
			return table[key]
		end,
	})
	
	local function onsoundemitter(__soundemitter)
		_soundemitter = __soundemitter
		return SoundEmitter	
	end
	
	inst:ListenForEvent("playeractivated", _OnPlayerActivated)
	inst:ListenForEvent("playeractivated", function(inst, player)
		if OnPlayerActivated ~= nil then
			Waffles.BranchUpvalue(OnPlayerActivated, "StartSoundEmitter", "_soundemitter", onsoundemitter)
		end
	end)
end)

if not TheNet:GetIsClient() then return end

local function PushMusicEX(PushMusic, inst, ...)
	if inst:HasTag("noattack") then
		inst._playingmusic = false
	else
		PushMusic(inst, ...)
	end
end

AddSimPostInit(function()
	pcall(Waffles.BranchUpvalue, _G.Prefabs.crabking.fn, "PushMusic", PushMusicEX)
end)